package com.yglab.sqpoll.android.settings;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.yglab.sqpoll.android.R;
import com.yglab.sqpoll.android.R.string;

import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

/**
 * The activity for Profile
 * 
 * @author HongGyun Bae
 */
public class ProfileActivity extends SherlockActivity {
	
	public static final String TAG = "ProfileActivity";
	private final int PIC_DIALOG = 1;

	private static final String TEMP_PHOTO_FILE = "temp.jpg"; // temporary file

	private static final int REQ_CODE_PICK_IMAGE = 700;
	private static final int REQ_CODE_TAKE_IMAGE = 800;
	
	
	ImageView mPictureButton;
	Button mSaveButton;
	EditText mEmail;
	String mCheckEmail; // variable for using checkEmail
	String mCheckMessage;
	Spinner mSpinner1;
	Spinner mSpinner2;
	int mNationIndex;
	Bitmap mUserPhoto;
		

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); // remove title bar
		setContentView(R.layout.profile);
		
		//Setting the ActionBar Sherlock
		//ActionBar actionBar = getSupportActionBar();
		//actionBar.setDisplayShowTitleEnabled(true);
		//actionBar.setHomeButtonEnabled(true);
		//actionBar.setDisplayHomeAsUpEnabled(true);
			
		
		// btnPic(set the photo)
		mPictureButton = (ImageView) findViewById(R.id.picBtn);
				
		mPictureButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showDialog(PIC_DIALOG);
			}
		});
		
		// 'name of nation', 'number of nation' spinner
		showSpinner();

		// email (variable)
		mEmail = (EditText) findViewById(R.id.email);
				 
		
		// btnSave (Button)
		mCheckMessage = getResources().getString(R.string.email_check);
		mSaveButton = (Button) findViewById(R.id.saveBtn);
		mSaveButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// email validity check
				mCheckEmail = (String) mEmail.getText().toString();
				if (checkEmail(mCheckEmail) == false) {
					Toast.makeText(getApplicationContext(),
							mCheckMessage, Toast.LENGTH_LONG).show();
				}
			}
		});

	}
	
	/**
	 * Back button using Actionbar Sherlock
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case android.R.id.home:
			Intent intent = new Intent(this,SettingsActivity.class);
			startActivity(intent);
			return true;
		}
			
		return super.onOptionsItemSelected(item);
	}

	/**
	 *  PIC_DIALOG
	 */
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PIC_DIALOG:
			Builder bld = new AlertDialog.Builder(this);
			bld.setTitle(getResources().getString(R.string.photo_set));
			bld.setPositiveButton(getResources().getString(R.string.photo_return), null);

			LinearLayout picLayout = (LinearLayout) View.inflate(
					ProfileActivity.this, R.layout.pic_dialog, null);

			bld.setView(picLayout);

			Button btnGallery = (Button) picLayout.findViewById(R.id.galBtn); // showing gallery
			Button btnCamera = (Button) picLayout.findViewById(R.id.cameraBtn); // taking picture

			btnGallery.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(
							Intent.ACTION_GET_CONTENT,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					intent.setType("image/*");
					intent.putExtra("crop", "true");
					intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
					intent.putExtra("outputFormat",
							Bitmap.CompressFormat.JPEG.toString());

					startActivityForResult(intent, REQ_CODE_PICK_IMAGE);

					dismissDialog(PIC_DIALOG);
				}
			});

			btnCamera.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent2, REQ_CODE_TAKE_IMAGE);
					dismissDialog(PIC_DIALOG);
				}
			});
			AlertDialog alertDialog = bld.create();
			return alertDialog;
		}
		return null;
	}

	public void showSpinner() {
		// 'name of nation' spinner
		mSpinner1 = (Spinner) findViewById(R.id.spinner01);
		ArrayAdapter adapter1 = ArrayAdapter.createFromResource(this,
				R.array.nation, R.layout.spinner_layout);
		adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSpinner1.setAdapter(adapter1);

		// Set the item of spinner2 pressing the item of spinner1
		mSpinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				mNationIndex = mSpinner1.getSelectedItemPosition();
				mSpinner2.setSelection(mNationIndex);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		// 'number of nation' spinner
		mSpinner2 = (Spinner) findViewById(R.id.spinner02);
		ArrayAdapter adapter2 = ArrayAdapter.createFromResource(this,
				R.array.nation_number, R.layout.spinner_layout);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSpinner2.setAdapter(adapter2);

	}

	/**
	 * method of email validity check
	 * @param email
	 * @return
	 */
	public boolean checkEmail(String email) {
		if (email.indexOf("@") == -1) {
			return false;
		}
		return true;
	}

	/**
	 * Return the route of temporary file
	 * @return
	 */
	private Uri getTempUri() {
		return Uri.fromFile(getTempFile());
	}

	/**
	 * Return the route of file in SDCARD
	 * @return
	 */
	private File getTempFile() {
		if (isSDCARDMOUNTED()) {
			File f = new File(Environment.getExternalStorageDirectory(),
					TEMP_PHOTO_FILE);
			try {
				f.createNewFile();
			} catch (IOException e) {
			}
			return f;
		} else
			return null;
	}

	/**
	 * Check if SDCARD is mounted or not
	 * @return
	 */
	private boolean isSDCARDMOUNTED() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED))
			return true;

		return false;
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent imageData) {
		super.onActivityResult(requestCode, resultCode, imageData);

		switch (requestCode) {

		case REQ_CODE_PICK_IMAGE:
			if (resultCode == RESULT_OK) {
				if (imageData != null) {
					String filePath = Environment.getExternalStorageDirectory()
							+ "/temp.jpg";
					System.out.println("path" + filePath);

					// decoding from temp.jpg to Bitmap
					Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
					mPictureButton.setImageBitmap(selectedImage);
				}
			}
			break;
		case REQ_CODE_TAKE_IMAGE:
			if (resultCode == RESULT_OK) {
				Bitmap profileBitmap = (Bitmap) imageData.getExtras().get(
						"data");

				mPictureButton.setImageBitmap(profileBitmap);
				mPictureButton.setScaleType(ImageView.ScaleType.FIT_XY);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
